/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name one by one, they are:
 *  defectiveProductForm
 *  DefectiveProductForm
 *  defective_product_form
 */



/***** variables declartion section, begin *****/
var defectiveProductFormItemInputMode = wacFormInputMode.add;
var defectiveProductFormItemObj = {};
var defectiveProductFormObj = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        initDefectiveProductFormItemFormDialog();

        initDefectiveProductFormItemForm();

        bindDefectiveProductFormItemEvents();
    }
);

function bindDefectiveProductFormItemEvents()
{
    $("#defectiveProductFormItemFormDialog").bind('dialogopen', function(event, ui)
    {
        initDefectiveProductFormItemFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.defectiveProductFormItem.name);//
    });

    $("#defectiveProductFormItemFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#defectiveProductFormItem_btnSubmit").bind('click', function (e)
    {
        submitDefectiveProductFormItemForm();
    });

    $("#defectiveProductFormItem_btnClose").bind('click', function (e)
    {
        $("#defectiveProductFormItemFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "")
        {
            $("div[aria-labelledby='ui-dialog-title-defectiveProductFormItemFormDialog']").remove();
            $("#defectiveProductFormItemFormDialog").remove();
        }
    });
}


function initDefectiveProductFormItemFormDialog()
{
//    wacDebugLog("initDefectiveProductFormItemFormDialog.");
    $("#defectiveProductFormItemFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 1060,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initDefectiveProductFormItemForm()
{
    $("#defectiveProductFormItemForm").validationEngine();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initDefectiveProductFormItemFormData()
{
    wacShowBlockUILoading("#defectiveProductFormItemFormDialog");
    $('#defectiveProductFormItem_axis_id, #defectiveProductFormItem_cotton_goods_category_id, #defectiveProductFormItem_color_id, #defectiveProductFormItem_jar_id, #defectiveProductFormItem_goods_category_id, #defectiveProductFormItem_goods_number_unit_code').empty();

    var params = {
        "data_format" : 'json',
        "defective_product_form_id": defectiveProductFormObj.id
    };

    $.ajax({
        url: BASE_URL + "defectiveProductFormItem/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initDefectiveProductFormItemFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initDefectiveProductFormItemFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['axis'].length;i++)
        {
            $('<option value="' + jsonData['items']['axis'][i].key +'">' + jsonData['items']['axis'][i].value +'</option>').appendTo("#defectiveProductFormItem_axis_id");
        }

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#defectiveProductFormItem_goods_number_unit_code");
        }

        for(i=0;i<jsonData['items']['cotton_goods_category'].length;i++)
        {
            $('<option value="' + jsonData['items']['cotton_goods_category'][i].key +'">' + jsonData['items']['cotton_goods_category'][i].value +'</option>').appendTo("#defectiveProductFormItem_cotton_goods_category_id");
        }
   }

   setupDefectiveProductFormItemFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#defectiveProductFormItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupDefectiveProductFormItemFormDefaultValues(defaultValueObj)
{
    $("#defectiveProductFormItem_defective_product_form_id").attr("value", defectiveProductFormObj.id);
    $("#defectiveProductFormItem_defective_product_form_code").attr("innerHTML", defectiveProductFormObj.code);
    $("#defectiveProductFormItem_production_order_code").attr("innerHTML", defectiveProductFormObj.production_order_code);
    $("#defectiveProductFormItem_supplier_name").attr("innerHTML", defectiveProductFormObj.supplier_name);
    $("#defectiveProductFormItem_factory_name").attr("innerHTML", defectiveProductFormObj.factory_name);

    if(defectiveProductFormItemInputMode == wacFormInputMode.add)   // use default values
    {
        $("#defectiveProductFormItem_id").attr("value", 0);
        $('#defectiveProductFormItem_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#defectiveProductFormItem_jar_id').flexbox(BASE_URL + 'jar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "jar_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#defectiveProductFormItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#defectiveProductFormItem_goods_number_unit_code option:[value='"+ defectiveProductFormObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#defectiveProductFormItem_axis_id option:[value='"+ defaultValueObj.axis_id +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#defectiveProductFormItem_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: defectiveProductFormItemObj.goods_category_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#defectiveProductFormItem_goods_category_id_input').val(defectiveProductFormItemObj.goods_category_name);

        $('#defectiveProductFormItem_jar_id').flexbox(BASE_URL + 'jar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: defectiveProductFormItemObj.jar_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "jar_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#defectiveProductFormItem_jar_id_input').val(defectiveProductFormItemObj.jar_name);

        $('#defectiveProductFormItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: defectiveProductFormItemObj.color_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#defectiveProductFormItem_color_id_input').val(defectiveProductFormItemObj.color_name);

        $("#defectiveProductFormItem_batch").attr("value", defectiveProductFormItemObj.batch);
        $("#defectiveProductFormItem_goods_number_unit_price").attr("value", defectiveProductFormItemObj.goods_number_unit_price);
        $("#defectiveProductFormItem_goods_number").attr("value", defectiveProductFormItemObj.goods_number);
        $("#defectiveProductFormItem_id").attr("value", defectiveProductFormItemObj.id);

        $("#defectiveProductFormItem_quota_amount").attr("value", defectiveProductFormItemObj.quota_amount);
        $("#defectiveProductFormItem_processing_fee").attr("value", defectiveProductFormItemObj.processing_fee);
        $("#defectiveProductFormItem_wheelbase").attr("value", defectiveProductFormItemObj.wheelbase);
        $("#defectiveProductFormItem_axis_time").attr("value", defectiveProductFormItemObj.axis_time);
        $("#defectiveProductFormItem_cotton_yarn_consume_amount").attr("value", defectiveProductFormItemObj.cotton_yarn_consume_amount);
        $("#defectiveProductFormItem_cotton_yarn_unit_consume").attr("value", defectiveProductFormItemObj.cotton_yarn_unit_consume);
        $("#defectiveProductFormItem_cotton_yarn_expect_consume").attr("value", defectiveProductFormItemObj.cotton_yarn_expect_consume);
        $("#defectiveProductFormItem_attrition_rate").attr("value", defectiveProductFormItemObj.attrition_rate);
        $("#defectiveProductFormItem_memo").attr("value", defectiveProductFormItemObj.memo);

        $("#defectiveProductFormItem_cotton_goods_category_id option:[value='"+ defectiveProductFormItemObj.cotton_goods_category_id +"']").attr('selected', 'selected');
        $("#defectiveProductFormItem_goods_number_unit_code option:[value='"+ defectiveProductFormItemObj.goods_number_unit_code +"']").attr('selected', 'selected');
        $("#defectiveProductFormItem_axis_id option:[value='"+ defectiveProductFormItemObj.axis_id +"']").attr('selected', 'selected');
    }

//wacDebugLog($.dump(defectiveProductFormItemObj));
//    wacDebugLog($.dump(defectiveProductFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("defectiveProductFormItemInputMode: " + defectiveProductFormItemInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

function defectiveProductFormItemOpenModuleForm(moduleFormName, moduleName, inputMode, rowid, parentId)
{
    defectiveProductFormItemInputMode = inputMode;

    if(parentId === undefined || parentId==0){
        defectiveProductFormObj = {};
    }
    else
    {
        defectiveProductFormObj = $("#defectiveProductFormList").getRowData(parentId);
    }

    if(rowid === undefined || rowid==0){
        defectiveProductFormItemObj = {};
    }
    else
    {
        defectiveProductFormItemObj = $("#defectiveProductFormList_" + defectiveProductFormObj.id + "_t").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateDefectiveProductFormItemForm()
{
    var validateFlag = true;

    if (!$("#defectiveProductFormItemForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    return validateFlag;
}

function submitDefectiveProductFormItemForm()
{
    if(!validateDefectiveProductFormItemForm()){
        return;
    }

    wacShowBlockUILoading("#defectiveProductFormItemFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(defectiveProductFormItemInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "defectiveProductFormItem/add";
    }
    else{
        submitUrl = BASE_URL + "defectiveProductFormItem/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#defectiveProductFormItemForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitDefectiveProductFormItemFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitDefectiveProductFormItemFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#defectiveProductFormList_" + defectiveProductFormObj.id + "_t").trigger("reloadGrid");
   }

   wacHideBlockUI("#defectiveProductFormItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/